package com.czkevin.cif;

import com.czkevin.cif.types.blocks.AdvancedCraftingBench;
import com.czkevin.cif.types.blocks.SteelBlock;
import com.czkevin.cif.types.items.Steel;

import java.util.*;


public class ItemRegister {

    private final static Map<String, CIFItem> items = new HashMap<>();

    private ItemRegister() { }

    private static final List<ItemRegisterListener> itemRegisterListeners = new LinkedList<>();
    public static void addRegisterListener(ItemRegisterListener listener) {
        itemRegisterListeners.add(listener);
    }

    static {
        addRegisterListener((x) -> x); // default
    }

    private static boolean inited = false;
    private static boolean started_init = false;
    public static void init() {
        if(inited || started_init) return;
        started_init = true;

        // Custom models
        register(new AdvancedCraftingBench());
        register(new SteelBlock());

        // Original models
        register(new Steel());

        inited = true;
    }
    
    public static void register(CIFItem item) {
        for(ItemRegisterListener listener : itemRegisterListeners) {
            item = listener.onRegister(item);
        }
        if(item.type() == null) throw new IllegalArgumentException("Invalid type type! ");
        if(items.containsKey(item.type())) throw new IllegalArgumentException("Item already registered! ");
        items.put(item.type(), item);
    }

    public static CIFItem get(String type) {
        if(type == null) return null;
        return items.get(type);
    }

    private static List<String> listTypes = null;
    private static long last_type_reload = 0L;
    public static List<String> getAllTypes() {
        if(!inited) return Collections.emptyList();
        if(listTypes == null || (System.currentTimeMillis() - last_type_reload) > 5000L) {
            listTypes = new LinkedList<>(items.keySet());
            last_type_reload = System.currentTimeMillis();
        }
        return listTypes;
    }


    public interface ItemRegisterListener {
        CIFItem onRegister(CIFItem toRegister);
    }

}
